package cn.lg.soar.core.util.easyexcel.translate;

import cn.lg.soar.common.util.reflect.SoarBeanUtils;
import cn.lg.soar.common.util.trans.annotations.Translate;
import cn.lg.soar.common.util.trans.model.TranslateContext;
import org.springframework.util.ConcurrentReferenceHashMap;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.Map;

/**
 * @author luguoxiang
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
class Utils {

    private final static Map<Field, InnerTranslateConverter<?>> CACHE = new ConcurrentReferenceHashMap<>();

    public static InnerTranslateConverter<?> getConverter(Field field) {
        return CACHE.computeIfAbsent(field, f -> {
            Annotation[] annotations = f.getAnnotations();
            for (Annotation annotation : annotations) {
                Translate translate;
                if (annotation instanceof Translate) {
                    translate = (Translate) annotation;
                } else {
                    Class<? extends Annotation> annotationClass = annotation.annotationType();
                    translate = annotationClass.getAnnotation(Translate.class);
                    if (translate == null) {
                        continue;
                    }
                }
                TranslateContext<?> translateContext = new TranslateContext<>(
                        f.getType(),
                        annotations,
                        SoarBeanUtils.getBean(translate.value()),
                        f
                );
                return new InnerTranslateConverter<>(translateContext, annotation);
            }
            return null;
        });
    }
}
